<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label-width="150px" label="产品颜色信息ID" prop="proTemplateSecondryId">
                <el-input v-model="queryParams.proTemplateSecondryId" placeholder="请输入产品颜色信息ID" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
            <!-- <el-form-item label="采购-修改前图片" prop="purchasingBeforePicurl">
        <el-input
          v-model="queryParams.purchasingBeforePicurl"
          placeholder="请输入采购-修改前图片"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购-修改后图片" prop="purchasingAfterPicurl">
        <el-input
          v-model="queryParams.purchasingAfterPicurl"
          placeholder="请输入采购-修改后图片"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
            <el-form-item label="" prop="productNo">
                <el-input v-model="queryParams.productNo" @keyup.enter.native="handleQuery" placeholder="请输入货号" clearable />
            </el-form-item>
            <el-form-item label-width="180px" label="采购-修改备注说明" prop="purchasingAccessoriesMark">
                <el-input v-model="queryParams.purchasingAccessoriesMark" placeholder="请输入采购-修改备注说明" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['product:history:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['product:history:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['product:history:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['product:history:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="historyList" @selection-change="handleSelectionChange"
            :row-style="{ height: '100px' }">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="产品颜色信息修改ID" align="center" prop="id" />
            <el-table-column label="产品颜色信息ID" align="center" prop="proTemplateSecondryId" /> -->
            <!-- <el-table-column label="修改前图片" align="center" prop="purchasingBeforePicurl" /> -->
            <el-table-column label="修改前图片" align="center" prop="purchasingBeforePicurl">
                <template #default="scope">
                    <el-popover effect="light" trigger="click" placement="left" width="auto"
                        v-show="scope.row.purchasingBeforePicurl">
                        <template #default>
                            <img :src='pjtUrl + scope.row.purchasingBeforePicurl'
                                style="width: 800px;height: 600px;object-fit: contain;">
                        </template>
                        <template #reference>
                            <img :src='pjtUrl + scope.row.purchasingBeforePicurl'
                                style="width: 100px; height: 100px;object-fit: contain;" />
                        </template>
                    </el-popover>
                </template>
                <!-- <template slot-scope="scope">
                                                                  <el-image style="width: 100px; height: 100px" :src="scope.row.logoFullUrl"></el-image></template> -->
            </el-table-column>
            <!-- <el-table-column label="修改后图片" align="center" prop="purchasingAfterPicurl" /> -->
            <el-table-column label="修改后图片" align="center" prop="purchasingAfterPicurl">
                <template #default="scope">
                    <el-popover effect="light" trigger="click" placement="left" width="auto"
                        v-show="scope.row.purchasingAfterPicurl">
                        <template #default>
                            <img :src='pjtUrl + scope.row.purchasingAfterPicurl'
                                style="width: 800px;height: 600px;object-fit: contain;">
                        </template>
                        <template #reference>
                            <img :src='pjtUrl + scope.row.purchasingAfterPicurl'
                                style="width: 100px; height: 100px;object-fit: contain;" />
                        </template>
                    </el-popover>
                </template>
                <!-- <template slot-scope="scope">
                                                                  <el-image style="width: 100px; height: 100px" :src="scope.row.logoFullUrl"></el-image></template> -->
            </el-table-column>
            <el-table-column label="修改备注说明" align="center" prop="purchasingAccessoriesMark" />
            <el-table-column width="150px" :label="'修改时间'" align="center" prop="createTime">
                <!-- <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}-{H}-{}') }}</span>
                </template> -->
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['product:history:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['product:history:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改特殊辅料修改记录对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body v-if="open
            ">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <!-- <el-form-item label="产品颜色信息ID" prop="proTemplateSecondryId">
                    <el-input v-model="form.proTemplateSecondryId" placeholder="请输入产品颜色信息ID" />
                </el-form-item> -->
                <!-- <el-form-item label="修改前图片" prop="purchasingBeforePicurl">
                    <el-input v-model="form.purchasingBeforePicurl" placeholder="请输入采购-修改前图片" />
                </el-form-item> -->
                <!-- //-----------新增或修改方法里上传图片 -->
                <!-- <el-form-item label="修改前图片" prop="purchasingBeforePicurl" label-width="40">
                    <el-upload :action="imgUpload.url" :headers="imgUpload.headers" list-type="picture-card" :limit="limit"
                        :on-exceed="handleExceed" :on-success="handlePictureSuccess" :before-upload="beforeAvatarUpload"
                        :on-preview="handlePictureCardPreview" :file-list="files" :on-change="changeFile1">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" v-if="purchasingBeforePicurl" :src="pjtUrl + purchasingBeforePicurl" alt="">
                    </el-dialog>
                </el-form-item> -->
                <el-form-item label="修改前图片" prop="purchasingBeforePicurl">
                    <!-- <el-upload :action="imgUpload.url" :headers="imgUpload.headers" list-type="picture-card" :limit="limit"
                                                                                                                                                :on-exceed="handleExceed" :on-success="handlePictureSuccess" :before-upload="beforeAvatarUpload"
                                                                                                                                                :on-preview="handlePictureCardPreview" :file-list="fileList" :on-change="changeFile2">
                                                                                                                                                <i class="el-icon-plus"></i>
                                                                                                                                            </el-upload>
                                                                                                                                            <el-dialog :visible.sync="dialogVisible">
                                                                                                                                                <img width="100%" v-if="imageUrl" :src="imageUrl" alt="">
                                                                                                                                                                                </el-dialog> -->
                    <el-upload ref="uploadpurchasingBeforePicurl" :action="imgUpload.url" :headers="imgUpload.headers"
                        list-type="picture-card" :on-change='changepurchasingBeforePicurl'
                        :file-list="filepurchasingBeforePicurl" multiple :on-success="uploadpurchasingBeforePicurl"
                        :on-remove="RemovepurchasingBeforePicurl">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div id="preview" @paste="handlepurchasingBeforePicurl">
                        <span><i class="el-icon-s-opportunity" style="color:#FB894C"></i>点击此处 将图片按Ctrl+V 粘贴至此处</span>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="修改后图片" prop="purchasingAfterPicurl">
                    <el-input v-model="form.purchasingAfterPicurl" placeholder="请输入采购-修改后图片" />
                </el-form-item>
                 -->
                <!-- <el-form-item label="修改后图片" prop="purchasingAfterPicurl" label-width="40">
                    <el-upload :action="imgUpload.url" :headers="imgUpload.headers" list-type="picture-card" :limit="limit"
                        :on-exceed="handleExceed" :on-success="handlePictureSuccessPic" :before-upload="beforeAvatarUpload"
                        :on-preview="handlePictureCardPreview" :file-list="fileList" :on-change="changeFile2">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" v-if="purchasingAfterPicurl" :src="pjtUrl + purchasingAfterPicurl" alt="">
                    </el-dialog>
                </el-form-item> -->
                <el-form-item label="修改后图片" prop="purchasingAfterPicurl">

                    <el-upload ref="uploadpurchasingAfterPicurl" :action="imgUpload.url" :headers="imgUpload.headers"
                        list-type="picture-card" :on-change='changepurchasingAfterPicurl'
                        :file-list="filepurchasingAfterPicurl" multiple :on-success="uploadpurchasingAfterPicurl"
                        :on-remove="RemovepurchasingAfterPicurl">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div id="preview" @paste="handlepurchasingAfterPicurl">
                        <span><i class="el-icon-s-opportunity" style="color:#FB894C"></i>点击此处 将图片按Ctrl+V 粘贴至此处</span>
                    </div>
                </el-form-item>
                <el-form-item label="修改备注说明" prop="purchasingAccessoriesMark">
                    <el-input v-model="form.purchasingAccessoriesMark" placeholder="请输入采购-修改备注说明" />
                </el-form-item>
                <!-- <el-form-item label="逻辑删除;0=未删除；1=已删除" prop="isDelete">
                    <el-input v-model="form.isDelete" placeholder="请输入逻辑删除;0=未删除；1=已删除" />
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listHistory, getHistory, delHistory, addHistory, updateHistory } from "@/api/product/history";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
    name: "History",
    data() {
        return {
            purchasingBeforePicurl: '',
            filepurchasingBeforePicurl: [],

            purchasingAfterPicurl: '',
            filepurchasingAfterPicurl: [],
            pjtUrl: process.env.VUE_APP_BASE_API,
            // 图片数量限制
            limit: 2,
            //页面上存的暂时图片地址List
            // files: [{ url: "" }],
            files: [],
            //页面上存的暂时logo图片地址List
            // fileList: [{ url: "" }],
            fileList: [],
            //图片地址
            imageUrl: "",
            dialogVisible: false,
            imgUpload: {
                // 设置上传的请求头部
                headers: {
                    Authorization: "Bearer " + getToken()
                },
                // 图片上传的方法地址:
                url: process.env.VUE_APP_BASE_API + "/common/upload",
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 特殊辅料修改记录表格数据
            historyList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                productNo: null,
                proTemplateSecondryId: null,
                purchasingBeforePicurl: null,
                purchasingAfterPicurl: null,
                purchasingAccessoriesMark: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                proTemplateSecondryId: [
                    { required: true, message: "产品颜色信息ID不能为空", trigger: "blur" }
                ],
            }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询特殊辅料修改记录列表 */
        getList() {
            let productNo = ''
            this.queryParam = this.$route.query.id
            if (this.$route.query.productNo) {
                productNo = this.$route.query.productNo
            } else {
                productNo = this.queryParams.productNo

            }

            this.loading = true;

            listHistory({ templateId: this.queryParam, productNo: productNo }).then(response => {
                this.historyList = response.rows;
                console.log(JSON.stringify(this.historyList));
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.files = undefined;//加的是这一行
            this.fileList = undefined;//加的是这一行
            this.form = {
                id: null,
                proTemplateSecondryId: null,
                purchasingBeforePicurl: null,
                purchasingAfterPicurl: null,
                purchasingAccessoriesMark: null,
                isDelete: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            // if (!this.$route.query.productNo) {
            //     this.$modal.msgError("禁止添加,请从颜色菜单-修改记录进入");
            //     return
            // }
            this.reset();
            this.open = true;
            this.title = "添加特殊辅料修改记录";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getHistory(id).then(response => {
                this.purchasingBeforePicurl = response.data.purchasingBeforePicurl
                this.purchasingAfterPicurl = response.data.purchasingAfterPicurl

                //图片回显
                this.filepurchasingBeforePicurl = response.data.purchasingBeforePicurl ? [
                    { url: process.env.VUE_APP_BASE_API + response.data.purchasingBeforePicurl }] : []//图片加的是这一行
                this.filepurchasingAfterPicurl = response.data.purchasingAfterPicurl ? [
                    { url: process.env.VUE_APP_BASE_API + response.data.purchasingAfterPicurl }] : []//logo图片加的是这一行
                this.form = response.data;
                this.open = true;
                this.title = "修改特殊辅料修改记录";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.form.templateId = this.$route.query.id
            this.form.purchasingBeforePicurl = this.purchasingBeforePicurl
            this.form.purchasingAfterPicurl = this.purchasingAfterPicurl
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateHistory(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addHistory(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList({ productNo: this.$route.query.productNo });
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除特殊辅料修改记录编号为"' + ids + '"的数据项？').then(function () {
                return delHistory(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('product/history/export', {
                ...this.queryParams
            }, `history_${new Date().getTime()}.xlsx`)
        },
        //图片上传前的相关判断
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return isJPG && isLt2M;
        },
        //图片预览
        handlePictureCardPreview(file) {
            this.purchasingBeforePicurl
                = file.url
            this.purchasingAfterPicurl = file.url
            // this.imageUrl = file.url;
            this.dialogVisible = true;
        },
        handlePictureSuccessPic(res, file) {
            this.purchasingAfterPicurl = file.response.fileName;
        },
        //图片修改前的回调
        handlePictureSuccess(res, file) {
            //设置图片访问路径 （url 后台传过来的的上传地址）
            // this.imageUrl = file.response.url;
            // const url = file.response.fileName;
            this.purchasingBeforePicurl = file.response.fileName;
            // console.log(JSON.stringify(url));
        },

        // 文件个数超出
        handleExceed() {
            this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
        },
        changeFile1(file, fileList) {
            if (fileList.length > 1) {
                this.files = fileList.slice(-1);

                // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
            }
            // this.fileSpecial = fileList;
        },
        changeFile2(file, fileList) {
            if (fileList.length > 1) {
                this.fileList = fileList.slice(-1);

                // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
            }
            // this.fileSpecial = fileList;
        },




        //修改前图片
        handlepurchasingBeforePicurl(event) {
            const items = (event.clipboardData || window.clipboardData).items;
            let file = null;
            if (!items || items.length === 0) {
                this.$message.error("当前浏览器不支持本地");
                return;
            }
            // 搜索剪切板items
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    file = items[i].getAsFile();
                    break;
                }
            }
            if (!file) {
                this.$message.error("粘贴内容非图片");
                return;
            }
            if (this.filepurchasingBeforePicurl.length >= this.limit) {
                this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`); // 图片数量超出
                return
            }
            this.$refs.uploadpurchasingBeforePicurl.handleStart(file); // 将粘贴过来的图片加入预上传队列
            this.$refs.uploadpurchasingBeforePicurl.submit(); // 提交图片上传队列
        },
        //上传
        changepurchasingBeforePicurl(file, fileList) {
            // this.fileList = fileList
            console.log('成功', file, fileList)
            console.log(JSON.stringify(file));
            console.log(JSON.stringify(fileList));
            if (fileList.length > 1) {
                this.filepurchasingBeforePicurl = fileList.slice(-1);

            }
        },
        RemovepurchasingBeforePicurl() {
            this.purchasingBeforePicurl = ''
        },

        uploadpurchasingBeforePicurl(res, file, fileList) {
            console.log(JSON.stringify(file.response.fileName));
            this.purchasingBeforePicurl = file.response.fileName

        },




        //修改后图片
        handlepurchasingAfterPicurl(event) {
            const items = (event.clipboardData || window.clipboardData).items;
            let file = null;
            if (!items || items.length === 0) {
                this.$message.error("当前浏览器不支持本地");
                return;
            }
            // 搜索剪切板items
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    file = items[i].getAsFile();
                    break;
                }
            }
            if (!file) {
                this.$message.error("粘贴内容非图片");
                return;
            }
            if (this.filepurchasingAfterPicurl.length >= this.limit) {
                this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`); // 图片数量超出
                return
            }
            this.$refs.uploadpurchasingAfterPicurl.handleStart(file); // 将粘贴过来的图片加入预上传队列
            this.$refs.uploadpurchasingAfterPicurl.submit(); // 提交图片上传队列
        },
        //上传
        changepurchasingAfterPicurl(file, fileList) {
            // this.fileList = fileList
            console.log('成功', file, fileList)
            console.log(JSON.stringify(file));
            console.log(JSON.stringify(fileList));
            if (fileList.length > 1) {
                this.filepurchasingAfterPicurl = fileList.slice(-1);

            }
        },
        RemovepurchasingAfterPicurl() {
            this.purchasingAfterPicurl = ''
        },

        uploadpurchasingAfterPicurl(res, file, fileList) {
            console.log(JSON.stringify(file.response.fileName));
            this.purchasingAfterPicurl = file.response.fileName

        },

    }
};
</script>
